package com.sdh.onlinemarket.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sdh.onlinemarket.common.annotation.AdminToken;
import com.sdh.onlinemarket.common.lang.Result;
import com.sdh.onlinemarket.common.util.DeleteFile;
import com.sdh.onlinemarket.common.util.GeneratID;
import com.sdh.onlinemarket.entity.Contractitem;
import com.sdh.onlinemarket.entity.Images;
import com.sdh.onlinemarket.entity.Item;

import com.sdh.onlinemarket.service.ContractitemService;
import com.sdh.onlinemarket.service.ImagesService;
import com.sdh.onlinemarket.service.ItemService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 施德昊
 * @since 2021-11-21
 */
@Api(tags = "图片相关模块")
@RestController
@RequestMapping("/images")
@Slf4j
public class ImagesController {

    @Autowired
    ItemService itemService;
    @Autowired
    ImagesService imagesService;
    @Autowired
    ContractitemService contractitemService;

    public static final int imagesize = 5;
    public static final int detailsize = 10;


    @ApiOperation(value = "获取商品头像")
    @GetMapping(value = "/getavtar",produces = MediaType.IMAGE_PNG_VALUE)
    @ResponseBody
    public byte[] getAvtar(String itemid) throws Exception {
        System.out.println("请求图片了！"+ LocalDateTime.now());

        Item item = itemService.getOne(new QueryWrapper<Item>().eq("itemid",itemid));
        String itemavtar;
        if(item == null || item.getIavtar() == null ){
            itemavtar =   "src/resources/images/示例图片.jpg";
        }else {
            itemavtar = item.getIavtar();
        }
        File file = new File(itemavtar);

        try {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        }catch (FileNotFoundException fileNotFoundException){
            log.warn("图片未找到--URL="+itemavtar);
            return null;
        }
    }

    @ApiOperation(value = "获取期货方案头像")
    @GetMapping(value = "/getcitemavtar",produces = MediaType.IMAGE_PNG_VALUE)
    @ResponseBody
    public byte[] getCItemAvatar(String id) throws Exception {
        System.out.println("请求图片了！"+ LocalDateTime.now());
        Contractitem contractitem = contractitemService.getOne(new QueryWrapper<Contractitem>().eq("id",id));
        String citemavtar;
        if(contractitem == null || contractitem.getIavatar() == null ){
            citemavtar =   "src/resources/images/示例图片.jpg";
        }else {
            citemavtar = contractitem.getIavatar();
        }
        File file = new File(citemavtar);

        try {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        }catch (FileNotFoundException fileNotFoundException){
            log.warn("图片未找到--URL="+citemavtar);
            return null;
        }
    }

    @ApiOperation(value = "获取子类头像")
    @GetMapping(value = "/getsubavtar",produces = MediaType.IMAGE_PNG_VALUE)
    @ResponseBody
    public byte[] getSubAvtar(String itemid) throws Exception {
        System.out.println("请求图片了！"+ LocalDateTime.now());
        Item item = itemService.getOne(new QueryWrapper<Item>().eq("itemid",itemid));
        String itemsubavtar;
        if(item == null || item.getSubavatar() == null ){
            itemsubavtar =   "src/resources/images/示例图片.jpg";
        }else {
            itemsubavtar = item.getSubavatar();
        }
        File file = new File(itemsubavtar);

        try {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        }catch (FileNotFoundException fileNotFoundException){
            log.warn("图片未找到--URL="+itemsubavtar);
            return null;
        }
    }

    @ApiOperation(value = "获取方案类型头像")
    @GetMapping(value = "/getclassic",produces = MediaType.IMAGE_PNG_VALUE)
    @ResponseBody
    public byte[] getClassic(String id) throws Exception {
        System.out.println("请求图片了！"+ LocalDateTime.now());
        Contractitem contractitem = contractitemService.getOne(new QueryWrapper<Contractitem>().eq("id",id));
        String citemclassic;
        if(contractitem == null || contractitem.getClassic() == null ){
            citemclassic =   "src/resources/images/示例图片.jpg";
        }else {
            citemclassic = contractitem.getIavatar();
        }
        File file = new File(citemclassic);

        try {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        }catch (FileNotFoundException fileNotFoundException){
            log.warn("图片未找到--URL="+citemclassic);
            return null;
        }
    }

    @ApiOperation(value = "根据图片id获取图片",notes = "包括商品和方案的滚动图和详情图")
    @GetMapping(value = "/getimages",produces = MediaType.IMAGE_PNG_VALUE)
    @ResponseBody
    public byte[] getImages(String imageid) throws Exception {

        Images images = imagesService.getOne(new QueryWrapper<Images>().eq("imageid",imageid));
        String imageurl;
        System.out.println(images);
        System.out.println(imageid);
        System.out.println(LocalDateTime.now());
        if(images == null || images.getImageurl() == null ){
            System.out.println("没有图片");
            imageurl = "src/resources/images/示例图片.jpg";//默认图片
        }else {
            imageurl = images.getImageurl();
        }

        File file = new File(imageurl);
        try {
            FileInputStream inputStream = new FileInputStream(file);
            byte[] bytes = new byte[inputStream.available()];
            inputStream.read(bytes, 0, inputStream.available());
            return bytes;
        }catch (FileNotFoundException fileNotFoundException){
            log.warn("图片未找到--URL="+imageurl);
            return null;
        }
    }

    @ApiOperation(value = "获取某个商品滚动图的id列表")
    @PostMapping("/getitemimage")
    @ResponseBody
    public Result getItemImage(String itemid){
        System.out.println(itemid);

        List<Images> imagesList = imagesService.list(new QueryWrapper<Images>()
                .eq("itemid",itemid)
                .eq("imagetype",0)
                .orderByAsc("imageorder")
        );

        System.out.println(imagesList);
        if (imagesList == null || imagesList.size() == 0){
            log.warn("商品没有滚动图--itemid="+itemid);
            return Result.fail("item has no image");
        }
        for (Images images:imagesList) {
            images.setImageurl(null);
        }
        return Result.succ("list image success",imagesList);
    }

    @ApiOperation(value = "获取某个方案滚动图的id列表")
    @PostMapping("/getcitemimage")
    @ResponseBody
    public Result getCItemImage(String id){
        System.out.println(id);

        List<Images> imagesList = imagesService.list(new QueryWrapper<Images>()
                .eq("id",id)
                .eq("imagetype",2)
                .orderByAsc("imageorder")
        );

        System.out.println(imagesList);
        if (imagesList == null || imagesList.size() == 0){
            log.warn("商品没有滚动图--id="+id);
            return Result.fail("item has no image");
        }
        for (Images images:imagesList) {
            images.setImageurl(null);
        }
        return Result.succ("list image success",imagesList);
    }

    @ApiOperation(value = "获取商品细节的图片id列表")
    @PostMapping("/getitemdetail")
    @ResponseBody
    public Result getItemDetail(String itemid){
        List<Images> imagesList = imagesService.list(new QueryWrapper<Images>()
                .eq("imagetype",1)
                .eq("itemid",itemid)
                .orderByAsc("imageorder"));
        if (imagesList == null || imagesList.size() == 0){
            log.warn("商品没有详情图--itemid="+itemid);
            return Result.fail("item has no image");
        }
        for (Images images:imagesList
        ) {images.setImageurl(null);
        }
        return Result.succ("list detail success",imagesList);

    }

    @ApiOperation(value = "获取方案细节的图片id列表")
    @PostMapping("/getcitemdetail")
    @ResponseBody
    public Result getCItemDetail(String id){
        List<Images> imagesList = imagesService.list(new QueryWrapper<Images>()
                .eq("imagetype",3)
                .eq("id",id)
                .orderByAsc("imageorder"));
        if (imagesList == null || imagesList.size() == 0){
            log.warn("方案没有详情图--id="+id);
            return Result.fail("item has no image");
        }
        for (Images images:imagesList
        ) {images.setImageurl(null);
        }
        return Result.succ("list detail success",imagesList);

    }

    @AdminToken
    @ApiOperation(value = "批量上传滚动图")
    @ApiImplicitParams({
            @ApiImplicitParam(name="files",value="文件",required=true,paramType="form",dataType = "file"),
            @ApiImplicitParam(name="itemid",value="商品id",required=true,paramType="form"),
    })
    @PostMapping("/uploadnewimage")
    @ResponseBody
    public Result uploadNewImage(MultipartFile[] files, HttpServletRequest req) {
        System.out.println("===========/Imageupload============");
        if(files == null){
            log.warn("没有传入文件");
            return Result.fail("no file");
        }
        if(files.length>imagesize){
            log.warn("太多图片传入失败");
            return Result.fail("to much image");
        }

        String itemid = req.getParameter("itemid");
        if(itemid == null){
            log.warn("参数itemid为空");
            return Result.fail("wrong param");
        }

        Item item = itemService.getOne(new QueryWrapper<Item>().eq("itemid", itemid));
        List<Images> imagesListT = imagesService.list(new QueryWrapper<Images>()
                .eq("itemid", itemid)
                .eq("imagetype",0));

        if (item == null) {
            log.warn("未找到商品--itemid="+itemid);
            return Result.fail("商品不存在");
        }
        if(imagesListT != null && imagesListT.size()>0){
            for (Images images:imagesListT){
                DeleteFile.deletefileB(images.getImageurl());
            }
        }

        imagesService.remove(new QueryWrapper<Images>()
                .eq("itemid", itemid)
                .eq("imagetype",0));

//        System.out.println(files);
        int i = 0;
        for (MultipartFile file : files) {
            String orginName = file.getOriginalFilename();
            System.out.println("orginName: " + orginName);
            // 没有后缀的本来的文件名
            String fileName = orginName.substring(0, orginName.indexOf("."));
            System.out.println("fileName: " + fileName);

            // 文件类型判断
            if (!orginName.endsWith(".png") && !orginName.endsWith(".jpg")  && !orginName.endsWith(".jpeg")&& !orginName.endsWith(".bmp") && !orginName.endsWith(".gif")) {
                log.warn("传入文件格式错误");
                return Result.fail("文件类型错误，上传图片类型");
            }
            // 创建一个文件夹存放文件
            File folder = new File("src/resources/images");
            if (!folder.exists()) {
                folder.mkdirs();
            }

            String imageid = String.valueOf(GeneratID.getGeneratID());
            // 重命名操作
            String newName ="image_" + imageid + ".png";
            System.out.println("newName: " + newName);
            Images images = new Images();
            images.setItemid(itemid);
            images.setImageid(imageid);
            images.setImageurl(folder + "\\" + newName);
            images.setImagetype(0);
            images.setImageorder(i++);
            System.out.println(images);

            try {
                // 保存成另一个文件 “imageid.png”
                file.transferTo(new File(folder, newName));
                imagesService.save(images);
            } catch (IOException e) {
                return Result.fail("失败");
            }
        }

        // 将上传的文件信息插入数据库，以便下载接口下载，LocalDateTime.now()返回的就是Datetime类型
        System.out.println("===========/fileupload/===========");
        log.info("成功传入文件--itemid="+itemid);
        return Result.succ("upload image success！");
    }


    @AdminToken
    @ApiOperation(value = "批量上传方案滚动图")
    @ApiImplicitParams({
            @ApiImplicitParam(name="files",value="文件",required=true,paramType="form",dataType = "file"),
            @ApiImplicitParam(name="id",value="方案id",required=true,paramType="form"),
    })
    @PostMapping("/uploadnewcitemimage")
    @ResponseBody
    public Result uploadNewcCItemImage(MultipartFile[] files, HttpServletRequest req) {
        System.out.println("===========/Imageupload============");
        if(files == null){
            log.warn("没有传入文件");
            return Result.fail("no file");
        }
        if(files.length>imagesize){
            log.warn("太多图片传入失败");
            return Result.fail("to much image");
        }

        String id = req.getParameter("id");
        if(id == null){
            log.warn("参数id为空");
            return Result.fail("wrong param");
        }

        Contractitem contractitem = contractitemService.getOne(new QueryWrapper<Contractitem>().eq("id", id));
        List<Images> imagesListT = imagesService.list(new QueryWrapper<Images>()
                .eq("id", id)
                .eq("imagetype",2));

        if (id == null) {
            log.warn("未找到方案--id="+id);
            return Result.fail("商品不存在");
        }

        if(imagesListT != null && imagesListT.size()>0){
            for (Images images:imagesListT){
                DeleteFile.deletefileB(images.getImageurl());
            }
        }
        imagesService.remove(new QueryWrapper<Images>()
                .eq("id", id)
                .eq("imagetype",2));
//        System.out.println(files);
        int i = 0;
        for (MultipartFile file : files) {
            String orginName = file.getOriginalFilename();
            System.out.println("orginName: " + orginName);
            // 没有后缀的本来的文件名
            String fileName = orginName.substring(0, orginName.indexOf("."));
            System.out.println("fileName: " + fileName);

            // 文件类型判断
            if (!orginName.endsWith(".png") && !orginName.endsWith(".jpg")  && !orginName.endsWith(".jpeg")&& !orginName.endsWith(".bmp") && !orginName.endsWith(".gif")) {
                log.warn("传入文件格式错误");
                return Result.fail("文件类型错误，上传图片类型");
            }
            // 创建一个文件夹存放文件
            File folder = new File("src/resources/images");
            if (!folder.exists()) {
                folder.mkdirs();
            }

            String imageid = String.valueOf(GeneratID.getGeneratID());
            // 重命名操作I
            String newName ="contractImage_" + imageid + ".png";
            System.out.println("newName: " + newName);
            Images images = new Images();
            images.setItemid(id);
            images.setImageid(imageid);
            images.setImageurl(folder + "\\" + newName);
            images.setImagetype(2);
            images.setImageorder(i++);
            System.out.println(images);

            try {
                // 保存成另一个文件 “imageid.png”
                file.transferTo(new File(folder, newName));
                imagesService.save(images);
            } catch (IOException e) {
                return Result.fail("失败");
            }
        }

        // 将上传的文件信息插入数据库，以便下载接口下载，LocalDateTime.now()返回的就是Datetime类型
        System.out.println("===========/fileupload/===========");
        log.info("成功传入文件--id="+id);
        return Result.succ("upload image success！");
    }

    @AdminToken
    @ApiOperation(value = "批量上传详情图")
    @ApiImplicitParams({
            @ApiImplicitParam(name="files",value="文件",required=true,paramType="form",dataType = "File"),
            @ApiImplicitParam(name="itemid",value="商品id",required=true,paramType="form"),
    })
    @PostMapping("/uploadnewdetail")
    @ResponseBody
    public Result uploadNewDetail(MultipartFile[] files, HttpServletRequest req) {

        System.out.println("===========/fileupload============");
        System.out.println("==========="+LocalDateTime.now()+"============");
        if(files == null){
            System.out.println("no file");
            return Result.fail("no file");
        }
        if(files.length>detailsize){
            System.out.println("to much image");
            return Result.fail("to much image");
        }

        String itemid = req.getParameter("itemid");
        if(itemid == null){
            System.out.println("wrong param");
            return Result.fail("wrong param");
        }

        Item item = itemService.getOne(new QueryWrapper<Item>().eq("itemid", itemid));
        List<Images> imagesListT = imagesService.list(new QueryWrapper<Images>()
                .eq("itemid", itemid)
                .eq("imagetype",1));

        if (item == null) {
            return Result.fail("商品不存在");
        }

        if(imagesListT != null && imagesListT.size()>0) {
            for (Images images : imagesListT) {
                DeleteFile.deletefileB(images.getImageurl());
            }
        }
        imagesService.remove(new QueryWrapper<Images>()
                .eq("itemid", itemid)
                .eq("imagetype",1));
//        System.out.println(files);
        int i = 0;
        for (MultipartFile file : files) {
            String orginName = file.getOriginalFilename();
            System.out.println("orginName: " + orginName);
            // 没有后缀的本来的文件名
            String fileName = orginName.substring(0, orginName.indexOf("."));
            System.out.println("fileName: " + fileName);

            // 文件类型判断
            if (!orginName.endsWith(".png") && !orginName.endsWith(".jpg") && !orginName.endsWith(".jpeg")&& !orginName.endsWith(".bmp") && !orginName.endsWith(".gif")) {
                log.warn("文件格式错误"+orginName);
                return Result.fail("文件类型错误，上传图片类型");
            }
            // 创建一个文件夹存放文件
            File folder = new File("src/resources/images");
            if (!folder.exists()) {
                folder.mkdirs();
            }

            String imageid = String.valueOf(GeneratID.getGeneratID());
            // 重命名操作
            String newName = "detail_" + imageid + ".png";
            System.out.println("newName: " + newName);
            Images images = new Images();
            images.setItemid(itemid);
            images.setImageid(imageid);
            images.setImageurl(folder + "\\" + newName);
            images.setImagetype(1);
            images.setImageorder(i++);
            System.out.println(images);

            try {
                // 保存成另一个文件 “imageid.png”
                file.transferTo(new File(folder, newName));
                imagesService.save(images);
            } catch (IOException e) {
                return Result.fail(e.getMessage());
            }
        }
        // 将上传的文件信息插入数据库，以便下载接口下载，LocalDateTime.now()返回的就是Datetime类型
        System.out.println("===========/fileupload/===========");
        return Result.succ("upload detail success！");
    }

    @AdminToken
    @ApiOperation(value = "批量上传方案详情图")
    @ApiImplicitParams({
            @ApiImplicitParam(name="files",value="文件",required=true,paramType="form",dataType = "File"),
            @ApiImplicitParam(name="itemid",value="商品id",required=true,paramType="form"),
    })
    @PostMapping("/uploadnewcitemdetail")
    @ResponseBody
    public Result uploadNewCItemDetail(MultipartFile[] files, HttpServletRequest req) {

        System.out.println("===========/cItem file detail upload============");
        System.out.println("==========="+LocalDateTime.now()+"============");

        if(files == null){
            System.out.println("no file");
            return Result.fail("no file");
        }
        if(files.length>detailsize){
            System.out.println("to much image");
            return Result.fail("to much image");
        }

        String id = req.getParameter("id");
        if(id == null){
            System.out.println("wrong param");
            return Result.fail("wrong param");
        }

        Contractitem contractitem = contractitemService.getOne(new QueryWrapper<Contractitem>().eq("id", id));

        List<Images> imagesListT = imagesService.list(new QueryWrapper<Images>()
                .eq("id", id)
                .eq("imagetype",3));

        if (contractitem == null) {
            return Result.fail("商品不存在");
        }

        if(imagesListT != null && imagesListT.size()>0) {
            for (Images images : imagesListT) {
                DeleteFile.deletefileB(images.getImageurl());
            }
        }
        imagesService.remove(new QueryWrapper<Images>()
                .eq("id", id)
                .eq("imagetype",3));
//        System.out.println(files);
        int i = 0;
        for (MultipartFile file : files) {
            String orginName = file.getOriginalFilename();
            System.out.println("orginName: " + orginName);
            // 没有后缀的本来的文件名
            String fileName = orginName.substring(0, orginName.indexOf("."));
            System.out.println("fileName: " + fileName);

            // 文件类型判断
            if (!orginName.endsWith(".png") && !orginName.endsWith(".jpg") && !orginName.endsWith(".jpeg")&& !orginName.endsWith(".bmp") && !orginName.endsWith(".gif")) {
                log.warn("文件格式错误"+orginName);
                return Result.fail("文件类型错误，上传图片类型");
            }
            // 创建一个文件夹存放文件
            File folder = new File("src/resources/images");
            if (!folder.exists()) {
                folder.mkdirs();
            }

            String imageid = String.valueOf(GeneratID.getGeneratID());
            // 重命名操作
            String newName = "contractDetail_" + imageid + ".png";
            System.out.println("newName: " + newName);
            Images images = new Images();
            images.setItemid(id);
            images.setImageid(imageid);
            images.setImageurl(folder + "\\" + newName);
            images.setImagetype(3);
            images.setImageorder(i++);
            System.out.println(images);

            try {
                // 保存成另一个文件 “imageid.png”
                file.transferTo(new File(folder, newName));
                imagesService.save(images);
            } catch (IOException e) {
                return Result.fail(e.getMessage());
            }
        }
        // 将上传的文件信息插入数据库，以便下载接口下载，LocalDateTime.now()返回的就是Datetime类型
        System.out.println("===========/fileupload/===========");
        return Result.succ("upload detail success！");
    }

    @AdminToken
    @ApiOperation(value = "上传商品头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name="files",value="文件",required=true,paramType="form",dataType = "file"),
            @ApiImplicitParam(name="itemid",value="商品id",required=true,paramType="form"),
    })
    @PostMapping("/uploadavatar")
    @ResponseBody
    public Result uploadAvatar(MultipartFile files, HttpServletRequest req) {
        System.out.println("===========/avatar upload============");

        String itemid = req.getParameter("itemid");

        if(itemid == null){
            return Result.fail("wrong param");
        }
        if(files == null){
            return Result.fail("no file");
        }
        String orginName = files.getOriginalFilename();
        System.out.println("orginName: " + orginName);
        // 没有后缀的本来的文件名
        String fileName = orginName.substring(0, orginName.indexOf("."));
        System.out.println("fileName: " + fileName);
        // 文件类型判断
        if (!orginName.endsWith(".png")&&!orginName.endsWith(".jpg")&&!orginName.endsWith(".bmp")&&!orginName.endsWith(".gif")&&!orginName.endsWith(".jpeg")) {
            log.warn("文件格式错误"+orginName);
            return Result.fail("文件类型错误，上传图片类型");
        }
        // 创建一个文件夹存放文件
        File folder = new File("src/resources/images");
        if (!folder.exists()) {
            folder.mkdirs();
        }

        Item item = itemService.getOne(new QueryWrapper<Item>().eq("itemid",itemid));
        if(item == null){
            return Result.fail("商品不存在");
        }
        if(item.getIavtar()!=null){
            File file = new File(item.getIavtar());
            if (file.exists()){//文件是否存在
                file.delete();//删除文件
                System.out.println("delete success");
            }
        }
        String imageid = String.valueOf(GeneratID.getGeneratID());
        // 重命名操作
        String newName ="avatar_"+imageid + ".png";
        System.out.println("newName: " + newName);

        item.setIavtar(folder+"/"+newName);
        System.out.println(item);

        try {
            // 保存成另一个文件 “imageid.png”
            files.transferTo(new File(item.getIavtar()));
            itemService.update(item,new QueryWrapper<Item>().eq("itemid",item.getItemid()));
        } catch (IOException e) {
            return Result.fail(e.getMessage());
        }

        // 将上传的文件信息插入数据库，以便下载接口下载，LocalDateTime.now()返回的就是Datetime类型
        System.out.println("===========/avatar upload/===========");
        return Result.succ("avatar upload success！",newName);
    }

    @AdminToken
    @ApiOperation(value = "上传方案头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name="files",value="文件",required=true,paramType="form",dataType = "file"),
            @ApiImplicitParam(name="itemid",value="商品id",required=true,paramType="form"),
    })
    @PostMapping("/uploadcavatar")
    @ResponseBody
    public Result uploadCAvatar(MultipartFile files, HttpServletRequest req) {
        System.out.println("===========/avatar upload============");

        String id = req.getParameter("id");

        if(id == null){
            return Result.fail("wrong param");
        }
        if(files == null){
            return Result.fail("no file");
        }

        String orginName = files.getOriginalFilename();
        System.out.println("orginName: " + orginName);
        // 没有后缀的本来的文件名
        String fileName = orginName.substring(0, orginName.indexOf("."));
        System.out.println("fileName: " + fileName);
        // 文件类型判断
        if (!orginName.endsWith(".png")&&!orginName.endsWith(".jpg")&&!orginName.endsWith(".bmp")&&!orginName.endsWith(".gif")&&!orginName.endsWith(".jpeg")) {
            log.warn("文件格式错误"+orginName);
            return Result.fail("文件类型错误，上传图片类型");
        }
        // 创建一个文件夹存放文件
        File folder = new File("src/resources/images");
        if (!folder.exists()) {
            folder.mkdirs();
        }

        Contractitem contractitem = contractitemService.getOne(new QueryWrapper<Contractitem>().eq("id", id));
        if(contractitem == null){
            return Result.fail("商品不存在");
        }
        if(contractitem.getIavatar()!=null){
            File file = new File(contractitem.getIavatar());
            if (file.exists()){//文件是否存在
                file.delete();//删除文件
                System.out.println("delete success");
            }
        }

        String imageid = String.valueOf(GeneratID.getGeneratID());
        // 重命名操作
        String newName ="cavatar_"+imageid + ".png";
        System.out.println("newName: " + newName);

        contractitem.setIavatar(folder+"/"+newName);
        System.out.println(contractitem);

        try {
            // 保存成另一个文件 “imageid.png”
            files.transferTo(new File(contractitem.getIavatar()));
            contractitemService.update(contractitem,new QueryWrapper<Contractitem>().eq("id",contractitem.getId()));
        } catch (IOException e) {
            return Result.fail(e.getMessage());
        }

        // 将上传的文件信息插入数据库，以便下载接口下载，LocalDateTime.now()返回的就是Datetime类型
        System.out.println("===========/contract avatar upload/===========");
        return Result.succ("contract avatar upload success！",newName);
    }

    @AdminToken
    @ApiOperation(value = "上传子类头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name="files",value="文件",required=true,paramType="form",dataType = "file"),
            @ApiImplicitParam(name="itemid",value="商品id",required=true,paramType="form"),
    })
    @PostMapping("/uploadsubavatar")
    @ResponseBody
    public Result uploadSubAvatar(MultipartFile files, HttpServletRequest req) {
        System.out.println("===========/subavatar upload============");

        String itemid = req.getParameter("itemid");
        if(itemid == null){
            return Result.fail("wrong param");
        }

        if(files == null){
            return Result.fail("no file");
        }

        String orginName = files.getOriginalFilename();
        System.out.println("orginName: " + orginName);
        // 没有后缀的本来的文件名
        String fileName = orginName.substring(0, orginName.indexOf("."));
        System.out.println("fileName: " + fileName);
        // 文件类型判断
        if (!orginName.endsWith(".png")&&!orginName.endsWith(".jpg")&&!orginName.endsWith(".jpeg")&&!orginName.endsWith(".bmp")&&!orginName.endsWith(".gif")) {
            log.warn("文件格式错误"+orginName);
            return Result.fail("文件类型错误，上传图片类型");
        }
        // 创建一个文件夹存放文件
        File folder = new File("src/resources/images");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        Item item = itemService.getOne(new QueryWrapper<Item>().eq("itemid",itemid));
        if(item == null){
            return Result.fail("商品不存在");
        }
        if(item.getSubavatar() != null){
            File file = new File(item.getSubavatar());
            if (file.exists()){//文件是否存在
                file.delete();//删除文件
                System.out.println("delete success");
            }
        }
        String imageid = String.valueOf(GeneratID.getGeneratID());
        // 重命名操作
        String newName ="subavatar_"+imageid + ".png";
        System.out.println("newName: " + newName);
        item.setSubavatar(folder+"/"+newName);
        System.out.println(item);

        try {
            // 保存成另一个文件 “imageid.png”
            files.transferTo(new File(folder, newName));
            List<Item> itemListTD = itemService.list(new QueryWrapper<Item>().eq("classic",item.getClassic()).eq("subclassic",item.getSubclassic()));
            for(Item itemT:itemListTD){
                itemT.setSubavatar(item.getSubavatar());
                itemService.update(itemT,new QueryWrapper<Item>().eq("itemid",itemT.getItemid()));
            }
        } catch (IOException e) {
            return Result.fail(e.getMessage());
        }
        // 将上传的文件信息插入数据库，以便下载接口下载，LocalDateTime.now()返回的就是Datetime类型
        System.out.println("===========/subavatar upload/===========");
        return Result.succ("subavatar upload success！",newName);
    }

    @AdminToken
    @ApiOperation(value = "上传方案子类头像")
    @ApiImplicitParams({
            @ApiImplicitParam(name="files",value="文件",required=true,paramType="form",dataType = "file"),
            @ApiImplicitParam(name="itemid",value="商品id",required=true,paramType="form"),
    })
    @PostMapping("/uploadcitemsubavatar")
    @ResponseBody
    public Result uploadCItemSubAvatar(MultipartFile files, HttpServletRequest req) {
        System.out.println("===========/contract subAvatar upload============");

        String id = req.getParameter("id");
        if(id == null){
            return Result.fail("wrong param");
        }

        if(files == null){
            return Result.fail("no file");
        }

        String orginName = files.getOriginalFilename();
        System.out.println("orginName: " + orginName);
        // 没有后缀的本来的文件名
        String fileName = orginName.substring(0, orginName.indexOf("."));
        System.out.println("fileName: " + fileName);
        // 文件类型判断
        if (!orginName.endsWith(".png")&&!orginName.endsWith(".jpg")&&!orginName.endsWith(".jpeg")&&!orginName.endsWith(".bmp")&&!orginName.endsWith(".gif")) {
            log.warn("文件格式错误"+orginName);
            return Result.fail("文件类型错误，上传图片类型");
        }
        // 创建一个文件夹存放文件
        File folder = new File("src/resources/images");
        if (!folder.exists()) {
            folder.mkdirs();
        }
        Contractitem contractitem = contractitemService.getOne(new QueryWrapper<Contractitem>().eq("id", id));
        if(contractitem == null){
            return Result.fail("商品不存在");
        }
        if(contractitem.getClassicavatar() != null){
            File file = new File(contractitem.getClassicavatar());
            if (file.exists()){//文件是否存在
                file.delete();//删除文件
                System.out.println("delete success");
            }
        }
        String imageid = String.valueOf(GeneratID.getGeneratID());
        // 重命名操作
        String newName ="contractSubavatar_"+imageid + ".png";
        System.out.println("newName: " + newName);

        contractitem.setClassicavatar(folder+"/"+newName);
        System.out.println(contractitem);

        try {
            // 保存成另一个文件 “imageid.png”
            files.transferTo(new File(folder, newName));
            contractitemService.update(contractitem,new QueryWrapper<Contractitem>().eq("id",id));
        } catch (IOException e) {
            return Result.fail(e.getMessage());
        }
        // 将上传的文件信息插入数据库，以便下载接口下载，LocalDateTime.now()返回的就是Datetime类型
        System.out.println("===========/contract subavatar upload/===========");
        return Result.succ("contract subavatar upload success！",newName);
    }

}
